<?php
/*
 * СПВ
 **/
class SP_Database_ActiveRecord
{
	private $fields=array();
	private $primary='id';
	private $table;
	private $is_new=true;
	private $is_saved=false;
	private $base;
	
	public function __construct($table, $fields, $base)
	{
		$this->defineTable($table);
		$this->defineFields($fields);
		$this->defineDatabase($base);
	}
	
	public function defineDatabase($base)
	{
		$this->base=$base;
	}
	
	public function defineTable($name)
	{
		$this->table=$name;
	}
	
	public function definePrimary($name)
	{
		$this->primary=$name;
	}
	
	public function defineFields($fields)
	{
		$values = array_fill(0,count($fields),null);
		$this->fields = array_combine($fields, $values);
	}
	
	public function fromRow($row)
	{
		foreach($this->fields as $name => $value)
		{
			$this->fields[$name]=$row[$name];
		}
		$this->is_new=false;
		$this->is_saved=true;
	}
	
	public function set($name,$value)
	{
		if( array_key_exists($name, $this->fields) )
		{
			$this->fields[$name]=$value;
			$this->is_saved=false;
		}
	}
	
	public function get($name)
	{
		return $this->fields[$name];
	}
	
	public function __set($name,$value)
	{
		$this->set($name, $value);
	}
	
	public function __get($name)
	{
		return $this->get($name);
	}
	
	public function isNew()
	{
		return $this->is_new;
	}
	
	public function isSaved()
	{
		return $this->is_saved;
	}
	
	public function read($pk_value)
	{
		$base=$this->base->getReader();
		$query="SELECT * FROM `".$this->table."` WHERE `".$this->primary."`='$pk_value' LIMIT 1";
		$row=$base->getAssocRow($query);
		if( empty($row) ) return false;
		$this->fromRow($row);
		return true;
	}
	
	public function delete()
	{
		if( !$this->isNew() )
		{
			$base=$this->base->getWriter();
			$query="DELETE FROM `".$this->table."` WHERE `".$this->primary."`='".$this->fields[$this->primary]."' LIMIT 1";
			if ($base->query($query))
			{
				$this->is_new=true;
				$this->is_saved=false;
			}
		}
	}
	
	public function save()
	{
		if( $this->isSaved() ) return true;
		$base=$this->base->getWriter();
		$to_save=$this->fields;
		if( $this->isNew() )
		{
			$base->query(SP_Database_QueryBuilder::insert($this->table,$to_save));
			if( $base->getResult() )
			{
				if( $this->fields[$this->primary]===null ) $this->fields[$this->primary]=$base->getLastInsertId();
				$this->is_new=false;
				$this->is_saved=true;
				return true;
			}
		}
		else
		{
			$where=array($this->primary => $this->fields[$this->primary]);
			$base->query(SP_Database_QueryBuilder::update($this->table,$to_save,$where,1));
			if( $base->getResult() )
			{
				$this->is_saved=true;
				return true;
			}
		}
		return false;		
	}
	
	public function getValues($with_pk=true)
	{
		$array=$this->fields;
		unset($array[$this->primary]);
		return $array;
	}
	
	public function setValues($array)
	{
		foreach($array as $key => $value)
		{
			$this->set($key, $value);
		}
	}
	
}